
/* GCSx
** GAME.CPP
**
** Game playing module- basic init, other top-level functionality
*/

/*****************************************************************************
** Copyright (C) 2003-2006 Janson
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
** 
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
*****************************************************************************/

#include "all.h"

WorldPlay* gameWorld = NULL;
Uint8* keystate = NULL;

// FPS Calculation (running averages)
Uint32 firstTicks = 0;
Uint32 frames = 0;
Uint32 lastTicks = 0;
double actualFPS;
double totalFPS;
#define COUNT_FPS 10
int inFPS;
double cumFPS[COUNT_FPS];

void calcActualFPS() { start_func
    // FPS this frame
    Uint32 ticks = SDL_GetTicks();
    if (ticks == lastTicks) --lastTicks;
    actualFPS = (double)1000.0 / (ticks - lastTicks);
    lastTicks = ticks;
    
    // Update running average
    totalFPS -= cumFPS[inFPS];
    totalFPS += actualFPS;
    cumFPS[inFPS] = actualFPS;
    if (++inFPS >= COUNT_FPS) inFPS = 0;
    
    // Place in titlebar
    string title = PRODUCT_NAME " - ";
    title += gameWorld->getTitle();
    title += formatString(" (%4.2lf FPS avg of 10 / %2.4lf ms avg overall)", totalFPS / COUNT_FPS, (ticks - firstTicks) / (double)(++frames));
    SDL_WM_SetCaption(title.c_str(), title.c_str());
}

void gcsxGameplay(const string& gameFile) throw_File { start_func
    keystate = SDL_GetKeyState(NULL);

    gameWorld = new WorldPlay(gameFile.c_str());

    string title = PRODUCT_NAME " - ";
    title += gameWorld->getTitle();
    SDL_WM_SetCaption(title.c_str(), title.c_str());

    // @TODO: This should be configurable per game
    // @TODO: throw_Video
    selectVideoMode(-1, -1, -1, -1, 0, 1);
    
    // @TODO: optimize enabling these modes-
    //  per layer (based on tileset and presence of layer alpha)
    //  per layer sprites (?)
    //  for desktop (simply on)
    oglAlphaMode(1, 1);
    
    gameWorld->gameStart();
    
    // Init FPS
    firstTicks = lastTicks = SDL_GetTicks();
    frames = 0;
    inFPS = 0;
    totalFPS = (double)0.0;
    for (int p = 0; p < COUNT_FPS; ++p)
        cumFPS[p] = (double)0.0;
}

void gcsxEndgame() { start_func
    if (gameWorld) {
        interpreterCleanup();
        delete gameWorld;
        gameWorld = NULL;
        initDefaultVideo();
        SDL_WM_SetCaption(PRODUCT_NAME, PRODUCT_NAME);
    }
}

int handleGameEvents(int (*eventFunc)(SDL_Event*)) { start_func
    // TEMPORARY SAMPLE EVENT HANDLING
    Scene* scene = gameWorld->getCurrentScene();

    SDL_Event event;
    while (eventFunc(&event)) {
        if (event.type == SDL_QUIT)
            return GAME_EXIT;
        if (event.type == SDL_KEYDOWN) {
            int pos = 0;
            SDLMod mod = KMOD_NONE;
            if (event.key.keysym.mod & KMOD_ALT) mod = (SDLMod)(mod | KMOD_ALT);
            if (event.key.keysym.mod & KMOD_CTRL) mod = (SDLMod)(mod | KMOD_CTRL);
            if (event.key.keysym.mod & KMOD_SHIFT) mod = (SDLMod)(mod | KMOD_SHIFT);
            while (int command = config->readShortcut(event.key.keysym.sym, mod, ++pos)) {
                switch (command) {
                    case VIEW_CONSOLE:
                        return GAME_CONSOLE;
                        
                    case FILE_CLOSEGAME:
                        return GAME_EXIT;

                    case FILE_RETURNGAME:
                        return GAME_MENU;

                    default:
                        break;
                }
            }
        }
    }

    if (scene) {
        if (keystate[SDLK_LEFT])
            scene->viewX(scene->viewX() + 1);
        if (keystate[SDLK_RIGHT])
            scene->viewX(scene->viewX() - 1);
        if (keystate[SDLK_UP])
            scene->viewY(scene->viewY() + 1);
        if (keystate[SDLK_DOWN])
            scene->viewY(scene->viewY() - 1);
    }

    return 0;
}

int gcsxGameloop() { start_func
    calcActualFPS();
    preGLScreenFlip();
    gameWorld->cycle();
    gameWorld->draw();
    postGLScreenFlip();
    // @TODO: actual proper delay/vsync wait
    SDL_Delay(1);

    return handleGameEvents(grabEvent);
}

void gcsxGameloopGui(int keysOk) { start_func
    calcActualFPS();
    preGLScreenFlip();
    gameWorld->cycle();
    gameWorld->draw();

    if (keysOk) {
        int result = handleGameEvents(grabEventGame);

        if (result == GAME_EXIT) 
            desktop->broadcastEvent(SDL_SPECIAL, SDL_CLOSEGAME);
        if (result == GAME_MENU)
            desktop->broadcastEvent(SDL_SPECIAL, SDL_QUITTOGAME);
        if (result == GAME_CONSOLE)
            desktop->broadcastEvent(SDL_COMMAND, VIEW_CONSOLE);
            
    }
}
